<template>
  <div class="page-container tasks-page">
    <el-row :gutter="20">
      <el-col :span="16">
        <div class="tasks-list card">
          <div class="card-header">
            <h2>我的任务</h2>
            <el-input
              v-model="searchQuery"
              placeholder="搜索任务"
              class="search-input"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>

          <el-tabs v-model="activeTab" class="mt-4">
            <el-tab-pane label="进行中" name="pending">
              <task-list
                :tasks="pendingTasks"
                :loading="loading"
                @start="startTask"
                @complete="completeTask"
                empty-text="暂无进行中的任务"
              />
            </el-tab-pane>
            <el-tab-pane label="已完成" name="completed">
              <task-list
                :tasks="completedTasks"
                :loading="loading"
                empty-text="暂无已完成的任务"
              />
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-col>

      <el-col :span="8">
        <div class="task-stats card">
          <h3>任务统计</h3>
          <div class="stats-content mt-4">
            <div class="stat-item">
              <div class="stat-label">总任务数</div>
              <div class="stat-value">{{ totalTasks }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">已完成</div>
              <div class="stat-value">{{ completedTasks.length }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">完成率</div>
              <div class="stat-value">{{ completionRate }}%</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">总经验</div>
              <div class="stat-value">{{ totalRewards.experience }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">总金币</div>
              <div class="stat-value">{{ totalRewards.coins }}</div>
            </div>
          </div>

          <el-progress
            :percentage="completionRate"
            :format="() => `完成进度 ${completionRate}%`"
            class="mt-4"
          />
        </div>

        <div class="task-tips card mt-4">
          <h3>小贴士</h3>
          <el-carousel height="150px" indicator-position="outside" class="mt-4">
            <el-carousel-item v-for="tip in tips" :key="tip.id">
              <div class="tip-content">
                <el-icon :size="24" class="tip-icon">
                  <component :is="tip.icon" />
                </el-icon>
                <p>{{ tip.content }}</p>
              </div>
            </el-carousel-item>
          </el-carousel>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useTaskStore } from '../stores/task'
import TaskList from '../components/TaskList.vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'TasksView',
  components: {
    TaskList
  },
  setup() {
    const taskStore = useTaskStore()
    const loading = ref(false)
    const searchQuery = ref('')
    const activeTab = ref('pending')

    const tips = [
      { 
        id: 1, 
        icon: 'Sunrise',
        content: '每天完成任务可以获得额外奖励！' 
      },
      { 
        id: 2, 
        icon: 'Star',
        content: '任务奖励会随着你的等级提升而增加。' 
      },
      { 
        id: 3, 
        icon: 'Timer',
        content: '注意查看任务的时间限制，按时完成可获得额外奖励。' 
      }
    ]

    const userTasks = computed(() => taskStore.userTasks || [])

    const filteredTasks = computed(() => {
      const query = searchQuery.value.toLowerCase()
      return userTasks.value.filter(task => 
        (task.title.toLowerCase().includes(query) ||
        task.description.toLowerCase().includes(query))
      )
    })

    const pendingTasks = computed(() => 
      filteredTasks.value.filter(task => 
        task.status === 'in_progress' || task.status === 'pending'
      )
    )

    const completedTasks = computed(() => 
      filteredTasks.value.filter(task => 
        task.status === 'completed'
      )
    )

    const totalTasks = computed(() => userTasks.value.length)

    const completionRate = computed(() => {
      const total = userTasks.value.length
      if (total === 0) return 0
      return Math.round((completedTasks.value.length / total) * 100)
    })

    const totalRewards = computed(() => ({
      experience: completedTasks.value.reduce((sum, task) => sum + (task.reward?.experience || 0), 0),
      coins: completedTasks.value.reduce((sum, task) => sum + (task.reward?.coins || 0), 0)
    }))

    const startTask = async (taskId) => {
      try {
        loading.value = true
        await taskStore.startTask(taskId)
        ElMessage.success('成功开始任务')
      } catch (error) {
        console.error('Failed to start task:', error)
        ElMessage.error('开始任务失败')
      } finally {
        loading.value = false
      }
    }

    const completeTask = async (taskId) => {
      try {
        loading.value = true
        await taskStore.completeTask(taskId)
        ElMessage.success('成功完成任务')
      } catch (error) {
        console.error('Failed to complete task:', error)
        ElMessage.error('完成任务失败')
      } finally {
        loading.value = false
      }
    }

    onMounted(async () => {
      try {
        loading.value = true
        await taskStore.fetchTasks()
      } catch (error) {
        console.error('Failed to fetch tasks:', error)
        ElMessage.error('获取任务列表失败')
      } finally {
        loading.value = false
      }
    })

    return {
      loading,
      searchQuery,
      activeTab,
      tips,
      pendingTasks,
      completedTasks,
      totalTasks,
      completionRate,
      totalRewards,
      startTask,
      completeTask
    }
  }
}
</script>

<style scoped>
.tasks-list {
  min-height: calc(100vh - 40px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}

.stats-content {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.stat-item {
  text-align: center;
  padding: 15px;
  background-color: var(--el-fill-color-light);
  border-radius: 8px;
}

.stat-label {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--el-text-color-primary);
}

.tip-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center;
  padding: 0 20px;
}

.tip-icon {
  margin-bottom: 16px;
  color: var(--el-color-primary);
}

.tip-content p {
  margin: 0;
  font-size: 16px;
  line-height: 1.5;
  color: var(--el-text-color-regular);
}
</style>
